﻿namespace EasyWeb
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    internal static partial class EWHelpers
    {
        public static class DataAnnotation
        {
            public static string GetDisplayNameForProperty(Type type, string propertyName)
            {
                EWDebug.IsNotNull(type, "type");
                EWDebug.IsNotNullOrEmpty(propertyName, "propertyName");

                var typeDescriptor = GetTypeDescriptor(type);

                var propertyDescriptor = typeDescriptor.GetProperties().Find(propertyName, true);
                if (propertyDescriptor == null)
                {
                    throw new ArgumentException(string.Format("The property {0} is not found in type {1}.", propertyName, type.FullName));
                }

                var attributes = propertyDescriptor.Attributes.Cast<Attribute>();

                var displayAttribute = attributes.OfType<DisplayAttribute>().FirstOrDefault<DisplayAttribute>();
                if (displayAttribute != null)
                {
                    return displayAttribute.GetName();
                }

                var displayNameAttribute = attributes.OfType<DisplayNameAttribute>().FirstOrDefault<DisplayNameAttribute>();
                if (displayNameAttribute != null)
                {
                    return displayNameAttribute.DisplayName;
                }

                return propertyName;
            }

            private static ICustomTypeDescriptor GetTypeDescriptor(Type type)
            {
                return new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);
            }
        }
    }
}
